package org.budo.storm.jdbc.connection;

import java.io.Serializable;
import java.sql.Connection;

import javax.sql.DataSource;

import org.apache.storm.jdbc.common.ConnectionProvider;
import org.budo.support.javax.sql.util.JdbcUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
@ToString
public class DataSourceConnectionProvider implements ConnectionProvider, Serializable {
    private static final long serialVersionUID = -9215410068147951995L;

    private transient DataSource dataSource;

    @Override
    public void prepare() {
        // log.debug("#28 prepare, this={}", this);
    }

    @Override
    public Connection getConnection() {
        try {
            return this.getDataSource().getConnection();
        } catch (Throwable e) {
            log.error("#36 getConnection error, dataSource=" + dataSource + ", e=" + e, e);
            throw new RuntimeException(e);
        }
    }

    @Override
    public void cleanup() {
        log.info("#42 cleanup, this=" + this);

        JdbcUtil.closeQuietly(this.getDataSource());
    }
}